package com.qf.flashlib.base;

import android.os.Looper;

import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.exception.ApiException;
import com.qf.flashlib.http.LoggerUtil;
import com.qf.flashlib.util.ViewUtil;

import io.reactivex.observers.DisposableObserver;

/**
 * 2018/11/9 15:32
 */
public abstract class BaseSubscriber<T> extends DisposableObserver<T> {

    private IView mRootView;
    private boolean autoShowLoading = true;

    public BaseSubscriber(IView mRootView) {
        this.mRootView = mRootView;
    }
    public BaseSubscriber(IView mRootView, boolean autoShowLoading) {
        this.mRootView = mRootView;
        this.autoShowLoading = autoShowLoading;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!isMainThread()) {
            return;
        }
        if (!ViewUtil.CheckNetworkState(FlashLib.getInstance().getContext())) {
            dispose();
            if (mRootView != null)
                mRootView.showMessage("手机网络异常");
            return;
        }
        if (mRootView!= null && autoShowLoading) {
            mRootView.showLoading();
        }
    }

    @Override
    public void onComplete() {
        if (mRootView != null) {
            mRootView.hideLoading();
        }
    }

    @Override
    public void onNext(T t) {
        if (mRootView != null) {
            mRootView.hideLoading();
            onSuccess(t);
        }

    }

    @Override
    public void onError(Throwable t) {
        if (mRootView == null)
            return;
        if (t instanceof ApiException) {
            LoggerUtil.e("--> e instanceof ApiException err:" + t);
            onError((ApiException) t);
            mRootView.onError((ApiException) t);
            mRootView.showMessage(t.getMessage());
        } else {
            LoggerUtil.e("--> e !instanceof ApiException err:" + t);
            ApiException apiException = ApiException.handleException(t);
            onError(apiException);
            mRootView.onError(apiException);
            mRootView.showMessage(apiException.getMessage());
        }
        mRootView.hideLoading();
    }

    public abstract void onSuccess(T t);

    public  void onError(ApiException e) {}

    private boolean isMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }
}
